package com.yxkj.railservicer.pager;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.classic.ClassicRefreshView;
import com.yxkj.railservicer.R;
import com.yxkj.railservicer.activity.MainActivity;
import com.yxkj.railservicer.adapter.SongDaAdapter;
import com.yxkj.railservicer.bean.SongDaBean;
import com.yxkj.railservicer.util.AppUtils;
import com.yxkj.railservicer.util.ContentUtil;
import com.yxkj.railservicer.util.JSONUtil;
import com.yxkj.railservicer.util.SPUtil;
import com.yxkj.railservicer.util.StringUtil;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * Created by sunyu on 2017/2/28.
 */

public class SongDa extends BasePager implements CanRefreshLayout.OnRefreshListener, CanRefreshLayout.OnLoadMoreListener {
    private static final String TAG = "TAG";

    private View view;
    private RecyclerView can_content_view;
    private List<SongDaBean> list;
    private SongDaAdapter adapter;
    private OkHttpClient client;
    private CanRefreshLayout refresh;
    private ClassicRefreshView can_refresh_header;
    private ClassicRefreshView can_refresh_footer;
    private JSONUtil jsonUtil;
    private MainActivity mainActivity;

    private List<String> idList;

    private List<String> phoneList;

    private ProgressDialog dialog;

    public SongDa(Activity activity) {
        super(activity);
        this.mainActivity = (MainActivity) activity;
    }

    @Override
    public void initData() {
        super.initData();
        if (view == null) {
            view = View.inflate(activity, R.layout.pager_base, null);

            can_content_view = (RecyclerView) view.findViewById(R.id.can_content_view);
            LinearLayoutManager layoutManager = new LinearLayoutManager(activity);
            can_content_view.setLayoutManager(layoutManager);

            jsonUtil = new JSONUtil();

            client = new OkHttpClient();


            can_refresh_header = (ClassicRefreshView) view.findViewById(R.id.can_refresh_header);
            can_refresh_footer = (ClassicRefreshView) view.findViewById(R.id.can_refresh_footer);

            can_refresh_header.setRefreshingStr("正在刷新");
            can_refresh_header.setPullStr("下拉刷新");
            can_refresh_header.setReleaseStr("松手刷新");
            can_refresh_header.setCompleteStr("刷新完成");

            can_refresh_footer.setRefreshingStr("正在加载");
            can_refresh_footer.setPullStr("上拉加载");
            can_refresh_footer.setReleaseStr("松手加载更多");
            can_refresh_footer.setCompleteStr("加载完成");

            refresh = (CanRefreshLayout) view.findViewById(R.id.refresh);
            //下拉刷新
            refresh.setOnRefreshListener(this);
            //上拉加载
            refresh.setOnLoadMoreListener(this);
            //刷新样式
            refresh.setStyle(0, 0);

            idList = new ArrayList<>();
            phoneList = new ArrayList<>();

            list = new ArrayList<>();
            adapter = new SongDaAdapter(activity, list, this);


            can_content_view.setAdapter(adapter);

            fl_basepager.addView(view);

            getInfo1();

        } else {
            onRefresh();
        }
    }

    /**
     * 同意用户取消订单
     *
     * @param position
     */

    public void confirm(final int position) {
        dialog = ProgressDialog.show(activity, "提示", "请稍后");

        String orderId = idList.get(position);

        String message = "?orderId=" + orderId;
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.agreeCancelOrder_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    final JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        list.remove(position);
                        idList.remove(position);
                        phoneList.remove(position);

                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mainActivity.getCount(SongDa.this, list.size() + "");
                                Toast.makeText(activity, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                                adapter.notifyDataSetChanged();
                            }
                        });

                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
            }
        });
    }

    /**
     * 拒绝用户取消订单
     *
     * @param position
     */
    public void cancel(final int position, String data) {
        dialog = ProgressDialog.show(activity, "提示", "请稍后");

        String orderId = idList.get(position);
        if (data == null) {
            data = " ";
        }

        String message = "?orderId=" + orderId + "&reason=" + data;

        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.refuseCancelOrder_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    final JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                SongDaBean bean = list.get(position);
                                bean.setOrderCancelStatus("9030");
                                adapter.notifyDataSetChanged();
                                dialog.dismiss();
                            }
                        });


                    } else {
                        toast(jsonObject.getString("message"));
                        dismiss();
                    }
                }
            }
        });
    }

    //发送短信
    public void message(int position) {
        dialog = ProgressDialog.show(activity, "提示", "正在发送短信，请稍等");
        String message = "?orderId=" + idList.get(position);

        final Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.noticeUserGet_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        toast("发送短信成功");
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                dismiss();
                Log.e(TAG, "发送短信验证码联网: " + jsonData);
            }
        });
    }

    //拨打电话
    public void phone(int position) {
        String phone = phoneList.get(position);
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);
    }

    public void dialog(final int position) {
        AppUtils.showMsgDialog(activity, 4, new AppUtils.MsgCallBackData2() {
            @Override
            public void clickMsg(Dialog d, String data, TextView textView) {
                Log.e("TAG", "===========" + data);
                if (data == null) {
                    data = " ";
                }
                deliveredGoods(position, data, textView, d);
            }
        });
    }


    /**
     * 送达
     */
    public void deliveredGoods(final int position, String data, final TextView textView, final Dialog d) {
//        dialog = ProgressDialog.show(activity, "提示", "请稍后");

        Log.e(TAG, "验证码：" + data);

        if (data == null) {
            data = " ";
        }
        String message = "?orderId=" + idList.get(position) + "&receiveCode=" + data;

        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.deliveredGoods_url + message)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                Log.e(TAG, "送达联网成功" + jsonData);
                if (jsonUtil.validate(jsonData)) {
                    final JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        Log.e(TAG, jsonObject.getString("message"));
                        list.remove(position);
                        idList.remove(position);
                        phoneList.remove(position);
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mainActivity.getCount(SongDa.this, list.size() + "");
                                d.dismiss();
                                Toast.makeText(activity, jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                                adapter.notifyDataSetChanged();
                            }
                        });
                    } else {
                        activity.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                textView.setVisibility(View.VISIBLE);
                            }
                        });
                    }

                }
//                dismiss();

            }
        });
    }

    private String orderStatus;
    private String count; //是否统计总数
    private int offset;//从哪一条之后开始取
    private int limit;//一次最多取多少条
    private String token;
    private String total;

    private void getInfo() {
        if (0 == pages) {
            list.clear();
            idList.clear();
            phoneList.clear();
        }
        token = SPUtil.getString(activity, "token");
        orderStatus = "7050";
        count = "true";
        limit = 20;
        offset = pages * limit;


        RequestBody body = new FormBody.Builder()
                .add("orderStatus", orderStatus)
                .add("count", count)
                .add("offset", String.valueOf(offset))
                .add("limit", String.valueOf(limit))
                .build();
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.query_url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray rows = jsonObject.getJSONObject("data").getJSONArray("rows");
                        total = jsonObject.getJSONObject("data").getString("total");
                        for (int i = 0; i < rows.size(); i++) {
                            JSONObject o = rows.getJSONObject(i);
                            phoneList.add(o.getString("customerPhoneNo"));
                            idList.add(o.getString("mainOrderId"));
                            list.add(new SongDaBean(o));
                        }

                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mainActivity.getCount(SongDa.this, total);
                        adapter.notifyDataSetChanged();
                        dialog.dismiss();
                    }
                });

                Log.e(TAG, "查询联网成功" + jsonData);
            }
        });
    }

    public void getInfo1() {
        if (0 == pages) {
            list.clear();
            idList.clear();
            phoneList.clear();
            adapter.notifyDataSetChanged();
        }
        token = SPUtil.getString(activity, "token");
        orderStatus = "7050";
        count = "true";
        limit = 20;
        offset = 0;
        Log.e(TAG, "getInfo1: +++++++++++++");
        RequestBody body = new FormBody.Builder()
                .add("orderStatus", orderStatus)
                .add("count", count)
                .add("offset", String.valueOf(offset))
                .add("limit", String.valueOf(limit))
                .build();
        Request request = new Request.Builder()
                .addHeader("token", token)
                .url(ContentUtil.query_url)
                .post(body)
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                toast("服务器繁忙，请稍后再试");
                dismiss();
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonData = response.body().string();
                if (jsonUtil.validate(jsonData)) {
                    JSONObject jsonObject = JSON.parseObject(jsonData);
                    if (jsonObject.getBoolean("success")) {
                        JSONArray rows = jsonObject.getJSONObject("data").getJSONArray("rows");
                        total = jsonObject.getJSONObject("data").getString("total");
                        for (int i = 0; i < rows.size(); i++) {
                            JSONObject o = rows.getJSONObject(i);
                            phoneList.add(o.getString("customerPhoneNo"));
                            idList.add(o.getString("mainOrderId"));
                            list.add(new SongDaBean(o));
                        }
                    } else {
                        toast(jsonObject.getString("message"));
                    }
                }
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mainActivity.getCount(SongDa.this, total);
                        adapter.notifyDataSetChanged();
                    }
                });

                Log.e(TAG, "查询联网成功" + jsonData);
            }
        });
    }

    public void setPages(int pages) {
        this.pages = pages;
    }

    @Override
    public void onRefresh() {
        dialog = ProgressDialog.show(activity, "提示", "正在查询订单，请稍等");
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages = 0;
//                list.clear();
//                idList.clear();
//                phoneList.clear();
                getInfo();
                refresh.refreshComplete();
            }
        }, 1000);

    }

    private int pages;

    @Override
    public void onLoadMore() {
        refresh.postDelayed(new Runnable() {
            @Override
            public void run() {
                pages++;
                getInfo();
                can_refresh_footer.setCompleteStr("");
                refresh.loadMoreComplete();
            }
        }, 1000);

    }

    private void toast(final String string) {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(activity, string, Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void dismiss() {
        activity.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                dialog.dismiss();
            }
        });
    }
}
